package com.itheima.health.config;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ClearRubbishImg {
    //设置最长等待时间为5分钟
    private static final Long MIN_DELETE_WAIT_TIME = 5 * 60 * 1000L;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    private SetMealService setMealService;


    //@Scheduled(cron="0/30 * * * * ?")//测试每30s执行一次
    //设置清理时间为凌晨2点
    @Scheduled(cron = "0 0 2 * * ?")
    public void clearRubbishImg() {
        log.info("开始清理垃圾图片");
        Set<String> rubbishImgs = redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        //遍历垃圾图片
        assert rubbishImgs != null;
        for (String rubbishImg : rubbishImgs) {
            log.info("[垃圾图片的名称:]"+rubbishImg);
            //获取图片上传到七牛云的时间
            long uploadTime = Long.parseLong(rubbishImg.split("_")[0]);
            //判断上传时间是否超过了最长等待时间
            if (System.currentTimeMillis() - uploadTime < MIN_DELETE_WAIT_TIME){
                //不超过，不清理此图片，清理下一个
                continue;
            }
            //判断图片是否被使用
            long count = setMealService.getNumOfImg(rubbishImg);
            if (count > 0) {
                //图片被数据库使用，不删除
                continue;
            }

            //图片没有被使用，删除图片
            qiniuUtils.deleteFileFromQiniu(rubbishImg);

            //将清理的图片从redis中移除
            redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(rubbishImg);
        }

        log.info("清理垃圾图片完成");
    }

}


